﻿using System;
using System.Collections.Generic;
using FitNesseRunner.Model;

namespace FitNesseRunner
{
	public class Context : IContext
	{
		private readonly HashSet<string> _imports;
		private readonly IReflectionProvider _reflectionProvider;

		public IReflectionProvider ReflectionProvider
		{
			get { return _reflectionProvider; }
		}

		public IDictionary<string, string> Variables { get; private set; }
		public string Path { get; private set; }
		public string RootPath { get; private set; }

		public Context(string path, ReflectionProviderFactory reflectionProviderFactory)
			: this(path, new HashSet<string>(), reflectionProviderFactory)
		{
		}

		public Context(string path, HashSet<string> imports, ReflectionProviderFactory reflectionProviderFactory)
		{
			Variables = new Dictionary<string, string>();
			_imports = imports;
			Path = path;
			
			var frontPageIndex = Path.IndexOf("\\FrontPage\\", StringComparison.InvariantCultureIgnoreCase);
			if (frontPageIndex == -1)
				throw new Exception("The path is not a valid FitNesse path (can't find FrontPage ancestor folder)");

			RootPath = Path.Substring(0, frontPageIndex);

			_reflectionProvider = reflectionProviderFactory.CreateReflectionProvider(imports);
		}

		public string LastScriptTableName { get; set; }

		public object LastScriptTableObject { get; set; }

		public void AddImports(IEnumerable<string> imports)
		{
			foreach (var import in imports)
			{
				_imports.Add(import);
			}
		}
	}
}